package com.example.shishaolong.warehousemanager.common;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日期相关的工具类
 */
public class DateUtil {

    private static String PATTERN = "yyyy-MM-dd HH:mm:ss";

    private DateUtil(){
    }

    /**
     * 获取到SimpleDateFormat实例
     * @param pattern
     * @return
     */
    public static DateFormat simpleDateFormat(String pattern){
        return new SimpleDateFormat(pattern);
    }

    /**
     * 日期格式化
     * @param formatPattern
     * @param date
     * @return
     * @throws ParseException
     */
    public static String dateFormat(String formatPattern, Date date) throws ParseException {
        String tempPattern = formatPattern!=null && "".equals(formatPattern)?formatPattern: PATTERN;
        return simpleDateFormat(tempPattern).format(date);
    }

    public static String dateFormat(Date date) throws ParseException {
        return simpleDateFormat(PATTERN).format(date);
    }

    public static String dateFormat(String formatPatternFrom, String formatPatternTo, String dateStr) throws ParseException {
        if(formatPatternFrom != null && !"".equals(formatPatternFrom)
                || formatPatternTo != null && !"".equals(formatPatternTo)
                ||dateStr != null && !"".equals(dateStr)){
            Date parse = simpleDateFormat(formatPatternFrom).parse(dateStr);
            return simpleDateFormat(formatPatternTo).format(parse);
        }
        return dateStr;
    }

    public static String dateFormat(String formatPatternFrom, String dateStr) throws ParseException {
        if(formatPatternFrom != null && !"".equals(formatPatternFrom)
                ||dateStr != null && !"".equals(dateStr)){
            Date parse = simpleDateFormat(formatPatternFrom).parse(dateStr);
            return simpleDateFormat(PATTERN).format(parse);
        }
        return dateStr;
    }

    /**
     * 返回当前日期时间的字符串
     * @return
     */
    public static String getCurrentDateStr(){
        return simpleDateFormat(PATTERN).format(new Date());
    }
}
